<template>
  <div class="trade-root">
    <van-sticky>
      <div class="search-box flex">
        <div class="input-box flex">
          <van-dropdown-menu active-color="#807E7F">
            <van-dropdown-item
              v-model="selectValue"
              :options="optionList"
              disabled
            />
          </van-dropdown-menu>
          <van-field v-model="inputValue" placeholder="搜索币种名称" />
        </div>
      </div>
    </van-sticky>

    <van-tabs
      v-model="active"
      swipeable
      color="#2F7AED"
      title-class="title"
      sticky
      offset-top=".8rem"
      @click="select"
    >
      <van-tab v-for="(item, index) in cat" :key="index" :title="item.title">
        <div class="list-box">
          <van-checkbox-group v-model="result" :ref="'checkboxGroup'+index">
            <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
              <van-list>
                <div
                  class="col"
                  v-for="(itemChild, indexChild) in lists"
                  :key="indexChild"
                >
                  <div class="check-box">
                    <van-checkbox
                      v-if="itemChild.label != '未设置'"
                      :name="itemChild.id"
                      icon-size="0.34rem"
                      :disabled="itemChild.label === '未设置' ? true : false"
                    ></van-checkbox>

                    <div
                      v-if="itemChild.label == '未设置'"
                      class="van-checkbox__icon van-checkbox__icon--round van-checkbox__icon--disabled"
                      style="font-size: 0.34rem;"
                    >
                      <i class="van-icon van-icon-success"></i>
                    </div>
                  </div>

                  <div class="name-box">
                    <div class="name">{{ itemChild.name }}/USDT</div>
                    <div class="num">数量 {{ itemChild.num }}</div>
                  </div>

                  <div class="label-box">
                    <div class="label">{{ itemChild.label }}</div>
                    <div v-if="itemChild.profit > 0" class="profit flex">
                      <div class="text">浮亏</div>
                      <div
                        class="profit"
                        :style="{
                          color: '#49C3AE',
                        }"
                      >
                        +{{ itemChild.profit }}
                      </div>
                    </div>
                    <div v-if="itemChild.profit == 0" class="profit">
                      <div class="text">浮亏</div>
                      <div
                        class="profit"
                        :style="{
                          color: '#A5A5A5',
                        }"
                      >
                        {{ itemChild.profit }}
                      </div>
                    </div>
                    <div v-if="itemChild.profit < 0" class="profit">
                      <div class="text">浮亏</div>
                      <div
                        class="profit"
                        :style="{
                          color: '#ce5065',
                        }"
                      >
                        {{ itemChild.profit }}
                      </div>
                    </div>
                  </div>

                  <div
                    v-if="itemChild.increase > 0"
                    class="btn red-bg"
                    :style="{
                      background: '#49C3AE',
                    }"
                  >
                    +{{ itemChild.increase }}%
                  </div>

                  <div
                    v-if="itemChild.increase == 0 && itemChild.label === '未设置' "
                    class="btn red-bg"
                    :style="{
                      background: '#A5A5A5',
                    }"
                  >
                    {{ itemChild.increase }}%
                  </div>

                   <div
                    v-if="itemChild.increase == 0 && itemChild.label != '未设置' "
                    class="btn red-bg"
                    :style="{
                      background: '#2d7afe',
                    }"
                  >
                    {{ itemChild.increase }}%
                  </div>

                  <div
                    v-if="itemChild.increase < 0"
                    class="btn red-bg"
                    :style="{
                      background: '#ce5065',
                    }"
                  >
                    {{ itemChild.increase }}%
                  </div>

                  <!-- 点击跳转 -->
                  <div
                    class="roter"
                    @click.stop="$router.push('/tradeHis?id=' + itemChild.id)"
                  ></div>
                </div>
                <div
                  v-if="!lists.length"
                  style="font-size: .2rem; margin: 2rem;"
                >
                  暂无数据
                </div>
              </van-list>
            </van-pull-refresh>
          </van-checkbox-group>
        </div>
      </van-tab>
    </van-tabs>

    <!-- 弹出层 -->
    <div class="operation-box">
      <div class="money-box flex-btw">
        <div class="money">当前账户剩余USDT：{{ accountBalance }}<font style="color:red;margin-right: 0.1rem;" v-if="!isMonitor">（禁止交易！）</font></div>
        <div class="btn flex">
          <van-checkbox
            v-if="show && lists.length"
            icon-size="16"
            v-model="checked"
            @click="checkAll"
          >
            全选
          </van-checkbox>
          <div class="text" @click="show = !show">批量设置</div>
          <van-icon :name="show ? 'arrow-down' : 'arrow-up'" />
        </div>
      </div>

      <div class="title-box" v-if="show">
        <div class="line"></div>
        <div class="title">仅针对已经勾选的所有币种进行操作</div>
      </div>

      <div class="btn-box" v-if="show">
        <div class="btn" @click="action(1)">
          <img src="../../assets/images/trade/1.png" alt="" />
          <div class="text">策略循环</div>
        </div>
        <div class="btn" @click="action(2)">
          <img src="../../assets/images/trade/2.png" alt="" />
          <div class="text">单次策略</div>
        </div>
        <div class="btn" @click="action(3)">
          <img src="../../assets/images/trade/3.png" alt="" />
          <div class="text">清仓卖出</div>
        </div>
        <div class="btn" @click="action(4)">
          <img src="../../assets/images/trade/4.png" alt="" />
          <div class="text">交易设置</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import mixin from "@/mixin.js";
import { Toast } from "vant";
import { TRADE_LIST, RULE_SET } from "@/api/api.js";

export default {
  name: "trade",
  mixins: [mixin],
  data() {
    return {
      // 搜索框数据
      inputValue: "",
      // 下拉框数据
      selectValue: 0,
      // 下拉框列表
      optionList: [
        {
          text: "火币",
          value: 0,
        },
      ],
      // 分类
      active: 0,
      cat: [
        { title: "全部" },
        { title: "策略循环" },
        { title: "单次策略" },
        { title: "停止补单" },
      ],
      // 列表数据
      lists: [],
      loading: false,
      finished: false,
      refreshing: false,
      // 是否x显示操作
      show: false,
      // 全选
      checked: false,
      checkedAll: false,
      result: [],
      curId: 0,
      // 暂存
      saveLists: [],
      accountBalance: 0.0,
      typeParam: {},
      // 可以选择的选项
      selectList: [],

      timerId : 0,

      isMonitor : true, // 用于判断是否允许交易
    };
  },
  created() {
    this.timerId = Math.random();
    this.getTradeList(0,this.timerId);
  },

  mounted() {
    // if (this.lists.length) {
    //   this.lists.map((val) => {
    //     if (val.label !== "未开启") {
    //       this.selectList.push(val);
    //     }
    //   });
    // }
  },

  methods: {
    action(param) {
      let ids = this.result.join(",");
      switch (param) {
        case 1:
          this.setType(1, ids);
          break;
        case 2:
          this.setType(2, ids);
          break;
				case 3:
					Toast('暂未开放')
					break;
        case 4:
          this.$router.push({ name: "Setting", params: { ids: ids } });
          break;
      }
    },
    async setType(type, ids) {
      this.typeParam.type = type;
      this.typeParam.coin_id = ids;
      const { data } = await this.$reqPost(RULE_SET, this.typeParam);
      if (data.status == 1) {
        Toast(data.info);
				this.getTradeList(this.curId);
        //this.getDetail(this.id);
      }
    },
    select(param) {
      this.getTradeList(param);
      this.curId = param;
      this.result = [];
      this.checked = false;
      this.checkedAll = false;
    },
    async getTradeList(type,timerId) {
      try{
        const { data } = await this.$reqGet(TRADE_LIST, {
          type: type,
        });
        this.curId = type;
        if (data.status == 1) {
          this.lists = data.data.list;
          this.saveLists = data.data.list;
          this.accountBalance = data.data.account_balance;
          this.isMonitor = data.data.isMonitor;
          this.refreshing = false;
          this.finished = true;
        } else {
          this.lists = data.data.list;
          this.saveLists = data.data.list;
          this.accountBalance = data.data.account_balance;
        }
      }catch (e) {
      }
      if(typeof(timerId) != 'undefined' && timerId) {
        this.timer(timerId);
      }
    },
    // 全选 与 反选
    checkAll() {
			console.log('操作全选反选')
			console.log(eval("this.$refs.checkboxGroup" +(this.active)));
			let item = eval("this.$refs.checkboxGroup" +(this.active))[0];
			this.$nextTick(function(){
				if (!this.checked) {
					item.toggleAll(false);
				}else{	  
					item.toggleAll(true);
				}
			})
      
    },
    onRefresh() {
      // 清空列表数据
      this.finished = false;
      // 重新加载数据
      // 将 refreshing 设置为 true，表示处于加载状态
      this.refreshing = true;
      this.getTradeList(this.curId);
    },
    search(value) {
      console.log(value);
      let listTmpArray = [];
      this.saveLists.forEach((item) => {
        if (item.name.toLowerCase().search(value.toLowerCase()) != -1) {
          listTmpArray.push(item);
        }
      });
      this.lists = listTmpArray;
      console.log(this.saveLists);
    },
    timer(timerId) {
      if(this.timerId != timerId) {
        return '';
      }
      return setTimeout(() => {
        this.getTradeList(this.curId,timerId);
      }, 1000);
    },
  },
  watch: {
    result(value) {
      this.selectList = [];
      if (this.lists.length) {
        this.lists.map((val) => {
          if (val.label !== "未设置") {
            this.selectList.push(val);
          }
        });
      }

      if (this.result.length != this.selectList.length) {
        this.checked = false;
      } else {
        this.checked = true;
      }
			console.log("监控result改变");
      console.log(value);
    },
    inputValue(n) {
      if (n != "") {
        this.search(n);
      } else {
        this.lists = this.saveLists;
      }
    },
    lists() {
      console.log("监控发生变化");
   //   this.timer();
    },
  },
  destroyed() {
    console.log("销毁");
    this.timerId = 0;
  },
};
</script>

<style lang="scss" scoped>
.trade-root {
  // background-color: #fff;
  .search-box {
    height: 0.8rem;
    background-color: #2d7afe;
    padding: 0 0.3rem;

    .input-box {
      box-sizing: border-box;
      width: 5.63rem;
      height: 0.6rem;
      padding-left: 1.13rem;
      background-color: #fff;
      border-radius: 0.4rem;
      overflow: hidden;
    }
  }

  .list-box {
    padding-bottom: 1.5rem;

    .col {
      position: relative;
      padding: 0.21rem 0.3rem;
      display: flex;
      align-items: center;
      background-color: #fff;
      border-bottom: 0.04rem solid #f9f8f8;

      &:nth-child(1) {
        border-top: 0.04rem solid #f9f8f8;
      }

      .check-box {
        margin-right: 0.22rem;

        .border {
        }
      }

      .name-box {
        width: 2.6rem;

        .name {
          text-align: left;
          font-size: 0.26rem;
          color: #141414;
          margin-bottom: 0.06rem;
          font-weight: bold;
          height: 0.4rem;
        }

        .num {
          text-align: left;
          font-size: 0.2rem;
          color: #a5a5a5;
        }
      }

      .label-box {
        .label {
          width: 1.22rem;
          height: 0.4rem;
          line-height: 0.4rem;
          background-color: #e1f1fe;
          font-size: 0.2rem;
          color: #3270aa;
          margin-bottom: 0.08rem;
        }

        .profit {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 0 0.02rem;

          .text {
            font-size: 0.2rem;
            color: #a5a5a5;
          }

          .profit {
            font-size: 0.2rem;

            &:nth-child(1) {
            }
          }
        }
      }

      .btn {
        position: absolute;
        right: 0.3rem;
        top: 0.3rem;
        width: 1.21rem;
        height: 0.55rem;
        line-height: 0.55rem;
        font-size: 0.2rem;
        color: #fff;
        border-radius: 0.1rem;
      }

      .roter {
        position: absolute;
        right: 0;
        width: calc(100% - 0.8rem);
        height: 100%;
      }
    }
  }

  .operation-box {
    position: fixed;
    bottom: 1rem;
    width: 100%;
    background-color: #f0f1f5;

    .money-box {
      height: 0.62rem;
      font-size: 0.24rem;
      padding: 0 0.3rem;

      .money {
        color: #2d7afe;
      }

      .btn {
        color: #2d7afe;
      }
    }

    .title-box {
      background-color: #fff;
      padding: 0 0.3rem;
      padding-top: 0.64rem;
      padding-bottom: 0.65rem;
      display: flex;
      align-items: center;

      .line {
        width: 0.07rem;
        height: 0.25rem;
        background-color: #2d7afe;
      }

      .title {
        font-size: 0.26rem;
        color: #141414;
        margin-left: 0.24rem;
      }
    }

    .btn-box {
      display: flex;
      justify-content: space-between;
      background-color: #fff;
      padding: 0 0.4rem;
      padding-bottom: 0.8rem;

      .btn {
        position: relative;
        width: 1.4rem;
        height: 1.4rem;

        img {
          width: 1.4rem;
          height: 1.4rem;
        }

        .text {
          top: 1.4rem;
          width: 100%;
          text-align: center;
          position: absolute;
          font-size: 0.26rem;
          color: #2d7afe;
        }
      }
    }
  }
  /deep/ .van-dropdown-menu__item--disabled .van-dropdown-menu__title {
    color: #323233;
  }
}
</style>
